package logic

import (
	"cloud-disk/core/models"
	"cloud-disk/core/utils"
	"context"
	"errors"

	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserRegisterLogic) UserRegister(req *types.UserRegisterRequest) (resp *types.UserRegisterResponse, err error) {
	result, err := l.svcCtx.RedisClient.Get(l.ctx, req.Email).Result()
	if err != nil {
		return nil, errors.New("验证码错误")
	}
	if result != req.Code {
		err = errors.New("验证码错误")
		return
	}
	//判断用户名是否存在
	var count int64
	err = l.svcCtx.DbConn.Table("user_basic").Where("name=?", req.Name).Count(&count).Error
	if err != nil {
		return
	}
	if count > 0 {
		err = errors.New("用户名已存在")
		return
	}
	//数据入库
	user := &models.User{
		Identity: utils.GetUUID(),
		Name:     req.Name,
		Password: utils.Md5Encode(req.Password),
		Email:    req.Email,
	}
	err = l.svcCtx.DbConn.Table("user_basic").Create(user).Error
	return
}
